#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

#define TYPE  2

struct msgbuf
{
	long type;
	char buf[20];
};
int main()
{
	//创建key
	key_t key = ftok(".",'q');
	if(-1 == key) 
	{
		printf("ftok 失败:%m\n");
		exit(-1);
	}
	printf("ftok %m\n");

	//创建消息队列
	int msgid = msgget(key,IPC_CREAT|0666);
	if(-1 == msgid) 
	{
		printf("创建消息队列失败:%m\n");
		exit(-1);
	}
	printf("创建消息队列%m\n");

	//接收
	int r;
	struct msgbuf msg;

	while(1)
	{
		memset(msg.buf,0,20);
		r = msgrcv(msgid,&msg,sizeof(msg),TYPE,IPC_NOWAIT);
		printf("r:%d,msg:%s,type:%u\n",r,msg.buf,msg.type);
		sleep(1);
	}


	return 0;
}
